import os
from PIL import Image
from flask import Blueprint, current_app, abort
from flask import send_from_directory
from pathlib import Path

_uploads_files = Blueprint('_uploads_files', __name__, url_prefix='/_uploads/files')


@_uploads_files.route('/<fname>')
def index(fname):
    base_path = current_app.config.get('UPLOADED_PHOTOS_DEST')
    tbase_path = os.path.join(base_path, 'thumbnail')
    file_path = current_app.config.get('UPLOADED_FILES_DEST')
    bpath = os.path.join(base_path, fname)
    tfname = fname[::-1]
    fsuffix = tfname[0:tfname.find('.') + 1][::-1]
    splitname = '_s_'

    imgtype = ".jpg .jpeg .png .bmp .gif"
    if (fsuffix not in imgtype) and (splitname not in fname):
        return send_from_directory(file_path, fname, as_attachment=False)

    if splitname in fname:
        justname = tfname[tfname.find(splitname) + 3:][::-1]
        tsize = tfname[tfname.find('.') + 1:tfname.find(splitname)][::-1].split('x')
        bpath = os.path.join(base_path, justname + fsuffix)
        if os.path.exists(bpath):
            isth, tname = makethumb(bpath, tsize[0], tsize[1], justname, fsuffix, base_path)
            # return str(isth)+','+tname
            if isth:
                return send_from_directory(tbase_path, tname, as_attachment=False)
            else:
                return send_from_directory(base_path, tname, as_attachment=False)
        else:
            return tfname
    else:
        if os.path.exists(bpath):
            return send_from_directory(base_path, fname, as_attachment=False)
        else:
            return bpath
            # abort(404)


def makethumb(bpath, twidth, theight, justname, fsuffix, base):
    """
    生成缩略图命名 格式：xxx_s_100x100.jpg
    bpaty 原图地址
    justname fsuffix 原图名称和
    base config中设定的文件保存路径
    twidth,theight 缩略图 宽高
    """
    itwidth = int(twidth)
    itheight = int(theight)
    tname = justname + "_s_" + "%sx%s" % (twidth, theight) + fsuffix
    filename = os.path.join(base, 'thumbnail', tname)
    # 如果已经存在缩略图就直接返回地址
    if os.path.exists(filename):
        return True, tname
    im = Image.open(bpath)
    mode=im.mode
    # 解决真正png背景变白问题，仍旧保持透明
    if fsuffix!='.png':
        if mode not in ('L', 'RGB'):
            if mode == 'RGBA':
                # 透明图片需要加白色底
                alpha = im.split()[3]
                bgmask = alpha.point(lambda x: 255 - x)
                im = im.convert('RGB')
                # paste(color, box, mask)
                im.paste((255, 255, 255), None, bgmask)
            else:
                im = im.convert('RGB')
    im.thumbnail((int(twidth), int(theight)))
    # 如果缩略图文件夹不存在则创建
    if not os.path.exists(os.path.join(base, 'thumbnail')):
        os.mkdir(os.path.join(base, 'thumbnail'))
    im.copy()
    try:
        im.save(filename)
    except IOError:
        return False, tname
    return True, tname
